import * as React from 'react';
import { styled } from '@mui/material/styles';
import { Menu, Typography, MenuItem, IconButton } from '@mui/material';
import { Link } from 'react-router-dom';
import { MainContext } from '../../context';
import AccountBoxIcon from '@mui/icons-material/AccountBox';
import { createRoute } from '../../utils';
import { CsrfTokenJson } from '../../extension-registry-types';

// 定义路由
export namespace UserLoginRoutes {
  export const OAUTH2 = createRoute(['oauth2', 'authorization']);
  export const GITHUB = createRoute([OAUTH2, 'github']);
  export const GITEE = createRoute([OAUTH2, 'gitee']);
}

// 样式定义
const PREFIX = 'UserLogin';
const classes = {
  avatar: `${PREFIX}-avatar`,
  link: `${PREFIX}-link`,
  menuItem: `${PREFIX}-menuItem`,
  menuButton: `${PREFIX}-menuButton`,
  logoutButton: `${PREFIX}-logoutButton`,
  icon: `${PREFIX}-icon`,
};

const Root = styled('div')(({ theme }) => ({
  [`& .${classes.avatar}`]: {
    width: '30px',
    height: '30px',
  },
  [`& .${classes.link}`]: {
    cursor: 'pointer',
    textDecoration: 'none',
  },
  [`& .${classes.menuItem}`]: {
    cursor: 'auto',
  },
  [`& .${classes.menuButton}`]: {
    border: 'none',
    background: 'none',
    padding: 0,
  },
  [`& .${classes.logoutButton}`]: {
    color: theme.palette.primary.dark,
  },
  [`& .${classes.icon}`]: {
    width: '30px',
    height: '30px',
    verticalAlign: '-0.15em',
    fill: 'currentColor',
    overflow: 'hidden',
  },
}));

// 主组件
class UserLoginComponent extends React.Component<UserLoginComponent.Props, UserLoginComponent.State> {
  static contextType = MainContext;
  declare context: MainContext;

  protected avatarButton: React.RefObject<HTMLButtonElement>;
  protected abortController = new AbortController();

  constructor(props: UserLoginComponent.Props) {
    super(props);

    this.avatarButton = React.createRef();

    this.state = {
      open: false,
    };
  }

  protected async updateCsrf() {
    try {
        const csrfToken = await this.context.service.getCsrfToken(this.abortController);
        const csrfTokenAsJson = csrfToken as CsrfTokenJson;
        this.setState({ csrf: csrfTokenAsJson.value });
    } catch (err) {
        this.context.handleError(err);
    }
  }

  protected readonly handleAvatarClick = () => {
    this.setState({ open: !this.state.open });
  };

  protected readonly handleClose = () => {
    this.setState({ open: false });
  };

  render(): React.ReactNode {
    return (
      <Root>
        <IconButton
          component = 'button'
          title='Log in'
          aria-label='Log in'
          onClick={this.handleAvatarClick}
          ref={this.avatarButton}
        >
          <AccountBoxIcon />
        </IconButton>

        <Menu
          open={this.state.open}
          anchorEl={this.avatarButton.current}
          transformOrigin={{ vertical: 'top', horizontal: 'right' }}
          onClose={this.handleClose}
        >
          <MenuItem className={classes.menuItem}>
            <Link
              onClick={this.handleClose}
              className={classes.link}
              to='/oauth2/authorization/gitee'
            >
              <Typography
                variant='button'
                color='textPrimary'
                onClick={() =>
                  window.location.href = this.context.service.getLoginUrlGitee()
                }
              >
                <svg className={classes.icon} aria-hidden='true'>
                  <use xlinkHref='#icon-gitee'></use>
                </svg>{' '}
                gitee
              </Typography>
            </Link>
          </MenuItem>
          <MenuItem className={classes.menuItem}>
            <Link
              onClick={this.handleClose}
              className={classes.link}
              to='/oauth2/authorization/github'
            >
              <Typography
                variant='button'
                color='textPrimary'
                onClick={() =>
                  window.location.href = this.context.service.getLoginUrl()
                }
              >
                <svg className={classes.icon} aria-hidden='true'>
                  <use xlinkHref='#icon-github'></use>
                </svg>{' '}
                github
              </Typography>
            </Link>
          </MenuItem>
        </Menu>
      </Root>
    );
  }
}

export namespace UserLoginComponent {
    // eslint-disable-next-line @typescript-eslint/no-empty-object-type
    export interface Props {}
    export interface State {
        open: boolean;
        csrf?: string;
    }
}

export const UserLogin = UserLoginComponent;
